/**
 * 好大夫
 * 根据二级科室采集疾病名称
 * @type {exports}
 */
module.exports = class {
  constructor(page) {
    this.model = think.model("puppeteer");
    this.page = page;
  }
  async evaluate() {
    const { page } = this;
    const links = await this.getCate();
    const list = [];
    for (let i = 0; i < links.length; i++) {
      const link = links[i];
      await page.goto(link.url);
      console.log(link);
      //await page.waitFor(3000);
      const depts = await this.getDeptLinks();
      list.push(...depts);
      //page.waitFor(3000);
      //console.log(link.name, "采集到", depts.length);
      if (depts.length === 0) {
        list.push(link);
      }
    }
    return list;
  }

  async getDeptLinks(cate) {
    const { page } = this;
    const list = await page.evaluate(() => {
      const items = document.querySelectorAll(".ksbd ul li a");
      const list = [];
      for (const item of items) {
        list.push({
          name: item.textContent,
          url: item.href
        });
      }
      return list;
    });
    return list;
  }

  async getCate() {
    const { page } = this;
    const list = await page.evaluate(() => {
      const items = document.querySelectorAll(".kstl a");
      const list = [];
      for (const item of items) {
        list.push({
          name: item.textContent,
          url: item.href
        });
      }
      return list;
    });
    return list;
  }

  async post(data) {
    const { page } = this;
    for (let i = 0; i < data.length; i++) {
      const item = data[i];
      console.log(item);
      await page.goto(item.url);
      const Handler = require("./HaodfJibingList");
      const handler = new Handler(page);
      const d = await handler.evaluate();
      console.log(d);
      await handler.post(d, item);
    }
  }
};
